<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--数据-->
            <el-col :span="4" :xs="24">
                <div class="head-container">
                    <el-input v-model="deptName" :placeholder="$locale('student.Enter')" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
                </div>
                <div class="head-container">
                    <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
                </div>
            </el-col>
            <!--数据-->
            <el-col :span="20" :xs="24">
                <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
                    <el-form-item :label="$locale('jobList.add.Student Name')" prop="studentName">
                        <el-input v-model="queryParams.studentName" :placeholder="$locale('jobList.add.Please enter the student name')" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item :label="$locale('geWudevice.add.state')" prop="status">
                        <el-select v-model="queryParams.status" :placeholder="$locale('geWudevice.add.state')" clearable style="width: 240px">
                            <el-option v-for="dict in dict.type.data_status" :key="dict.value" :label="dict.label" :value="+dict.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="$locale('student.Student email')" prop="contactEmail">
                        <el-input v-model="queryParams.contactEmail" :placeholder="$locale('student.Please enter the student email address')" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $locale('geWudevice.add.search for') }}</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $locale('geWudevice.reset') }}</el-button>
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">{{ $locale('classList.add.added') }}</el-button>
                        <el-button type="info" plain  icon="el-icon-upload2" size="mini" @click="openImportTable">{{ $locale('student.import') }}</el-button>
                    </el-col>
                </el-row>

                <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55">
                    </el-table-column>
                    <el-table-column :label="$locale('student.student')" align="center" key="studentName" prop="studentName">
                    </el-table-column>
                    <el-table-column :label="$locale('jobList.add.email')" align="center" key="contactEmail" prop="contactEmail" width="160">
                    </el-table-column>
                    <el-table-column :label="$locale('myClass.add.School Name')" align="center" key="schoolName" prop="schoolName">
                    </el-table-column>
                    <el-table-column :label="$locale('classList.add.class name')" align="center" key="className" prop="className">
                    </el-table-column>
                    <el-table-column :label="$locale('classList.add.Teacher in charge')" align="center" key="teacherName" prop="teacherName">
                    </el-table-column>
                    <el-table-column sortable column-key="status" :filters="[{text: $locale('classList.normal'), value: '1'}, {text: $locale('classList.freeze'), value: '0'}]" :label="$locale('jobList.job status')" align="center" key="status" prop="status">
                        <template slot-scope="scope">
                            <span v-for="item in dict.type.data_status">
                                <el-tag v-if="item.value == scope.row.status" :type="scope.row.status == 0?'success':'danger'" effect="dark">
                                    {{ item.label }}
                                </el-tag>
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column :label="$locale('student.Facial recognition frequency')" align="center" key="facialNum" prop="facialNum">
                    </el-table-column>
                    <el-table-column :label="$locale('student.Last login time')" align="center" key="loginDate" prop="loginDate">
                    </el-table-column>
                    <el-table-column :label="$locale('formMarkering.list.operate')" align="center" width="300" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">{{ $locale('classList.add.modify') }}</el-button>
                            <el-button type="text" size="mini" @click="handleFreeze(scope.row)">{{scope.row.status == 0?$locale('classList.freeze'):$locale('classList.thaw')}}</el-button>
                            <el-button type="text" size="mini" @click="handleUpdate(scope.row,true)">{{ $locale('geWudevice.view') }}</el-button>
                            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">
                              {{ $locale('formMarkering.list.delete') }}</el-button>
                            <el-button size="mini" type="text" @click="handleResetting(scope.row)">{{ $locale('school.add.Password Reset') }}</el-button>
                            <el-button size="mini" type="text" @click="handleExperiment(scope.row)">{{ $locale('student.add.experiment.experiment') }}</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
            </el-col>
        </el-row>

        <!-- 添加 -->
        <add ref="add" @getList="getList" :deptOptions="deptOptions"></add>
        <experiment ref="experiment" @getList="getList" />
        <import-table :import-url="'/school/student/importData'" exportUrl="school/student/importTemplate" :exportName="$locale('student.Student data')" ref="import" @ok="getList" />
        <el-dialog :title="$locale('school.add.Password Reset')" :visible.sync="open" width="500px">
            <el-form :model="loginForm" ref="loginForm" size="small" label-width="100px" :rules="rules">
                <el-form-item :label="$locale('myClass.add.Login password')" prop="oldPassword">
                    <el-input v-model="loginForm.oldPassword" :placeholder="$locale('school.add.Set a login password of 6 to 20 digits')" />
                </el-form-item>
                <el-form-item :label="$locale('school.add.Confirm password')" prop="password">
                    <el-input v-model="loginForm.password" :placeholder="$locale('classList.Please enter your login password again')" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">{{ $locale('school.add.Submit') }}</el-button>
                <el-button @click="open = false">{{ $locale('classList.add.Cancel') }}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { deleteById, list, setStatus, setStatusByIds, resetPwd } from "@/api/myClass/student";
import importTable from "@/components/ImportTemplate/index.vue";
import experiment from "./add/experiment.vue"
import { getClassList } from "@/api/myClass/classList";
import add from './add/index.vue'
import { getNames } from '@/utils/index'

export default {
    name: "student",
    dicts: ['data_status'],
    components: { add, importTable, experiment },
    data () {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 用户表格数据
            studentList: [],
            // 弹出层标题
            title: "",
            loginForm: {
                id: '',
                password: '',
                oldPassword: ''
            },
            // 部门树选项
            deptOptions: undefined,
            // 是否显示弹出层
            open: false,
            // 部门名称
            deptName: undefined,
            // 表单参数
            defaultProps: {
                children: 'zones',
                isLeaf: 'leaf',
                label: "name"
            },
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                studentName:'',
                status:'',
                contactEmail:''
            },
            // 表单校验
            rules: {
                oldPassword: [
                    { required: true, message: this.$locale('classList.Please enter your login password'), trigger: "blur" },
                    { min: 6, max: 20, message: this.$locale('classList.Password length is 6 to 20 digits'), trigger: 'blur' }
                ],
                password: [
                    { required: true, message: this.$locale('classList.Please enter your login password again'), trigger: "blur" },
                    { min: 6, max: 20, message: this.$locale('classList.Password length is 6 to 20 digits'), trigger: 'blur' },
                    { validator: this.validatePasswordConfirm, trigger: 'blur' }
                ]
            }
        };
    },
    watch: {
        // 根据名称筛选部门树
        deptName (val) {
            this.$refs.tree.filter(val);
        }
    },
    created () {
        this.getList();
        this.getDeptTree();
    },
    computed: {
        userName () {
            return this.$store.getters.name; // 使用 Vuex 的 getter 获取用户姓名
        }
    },
    methods: {
        /** 查询用户列表 */
        getList () {
            this.loading = true;
            list(this.queryParams).then(({ data }) => {
                this.studentList = data.records;
                this.total = data.total;
                this.loading = false;
            });
        },
        filterHandler (value, row, column) {
            const property = column['property'];
            return row[property] == value;
        },
        validatePasswordConfirm (rule, value, callback) {
            if (value === '') {
                callback(new Error(this.$locale('classList.Please enter your login password again')));
            } else if (value !== this.loginForm.password) {
                callback(new Error(this.$locale('classList.Entered passwords differ')));
            } else {
                callback();
            }
        },
        /** 打开导入表弹窗 */
        openImportTable () {
            this.$refs.import.handleImport()
        },
        /** 查询部门下拉树结构 */
        getDeptTree () {
            getClassList().then(response => {
                this.deptOptions = response.data.map(item => {
                    item['name'] = item.className;
                    return item;
                });

            })
        },
        /** 修改按钮操作 */
        handleResetting (row) {
            this.resetForm("loginForm");
            this.loginForm.id = row.id
            this.open = true
        },
        handleExperiment (row) {
            this.$refs.experiment.show(row)
        },
        /** 新增按钮操作 */
        handleAdd () {
            this.$refs.add.handleAdd()
        },
        /** 修改按钮操作 */
        handleUpdate (row, disabled) {
            this.$refs.add.handleUpdate(row, disabled)
        },
        /** 冻结按钮操作 */
        handleFreeze (row) {
            const Ids = row && row.id || this.ids;
            this.$modal.confirm(this.$locale('geWudevice.tip4') + getNames(this.studentList, Ids, 'studentName') + this.$locale('geWudevice.tip2')).then(() => {
                if (row && row.id) {
                    setStatus({id:Ids}).then(() => this.getList())
                } else {
                    setStatusByIds({id:Ids}).then(() => this.getList())
                }
            }).then((res) => {
                if (res.code == 200) this.$modal.msgSuccess(this.$locale('geWudevice.tip5'));
            }).catch(() => { });
        },
        // 筛选节点
        filterNode (value, data) {
            if (!value) return true;
            return data.name.indexOf(value) !== -1;
        },
        // 节点单击事件
        handleNodeClick (data) {
            if (data.className) {
                this.queryParams.classId = [data.id];
                this.handleQuery();
            }
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["loginForm"].validate(valid => {
                if (valid) {
                    resetPwd(this.loginForm).then(response => {
                        this.$modal.msgSuccess(this.$locale('geWudevice.add.tip5'));
                        this.getList();
                        this.open = false;
                    });
                }
            });
        },
        /** 搜索按钮操作 */
        handleQuery () {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery () {
            this.resetForm("queryForm");
            this.queryParams.classId = undefined;
            this.$refs.tree.setCurrentKey(null);
            this.handleQuery();
        },
        /** 删除按钮操作 */
        handleDelete (row) {
            const Ids = row.id || this.ids;
            this.$modal.confirm(this.$locale('geWudevice.tip1') +  getNames(this.studentList, Ids, 'studentName') + this.$locale('geWudevice.tip2')).then(function () {
                return deleteById({ id: Ids });
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess(this.$locale('geWudevice.tip3'));
            }).catch(() => { });

        },
        handleSelectionChange (selection) {
            this.ids = selection.map(item => item.id);
        },
    }
};
  </script>
    <style lang="scss" scoped>
::v-deep .el-table__row--level-1 .el-checkbox {
    display: none;
}
</style>
